package tw.asap.plus.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.User;
import tw.asap.plus.entity.response.ResponseDataWrapper;
import tw.asap.plus.network.config.HRetrofitCreator;
import tw.asap.plus.network.service.UserAuthService;
import tw.asap.plus.ui.AsapBaseActivity;
import tw.asap.plus.ui.custom.AppBar;
import tw.asap.plus.utils.T;
import tw.asap.plus.utils.Toaster;

/**
 * Description:
 * Created:      [15/11/6]
 * Author:       [Yang]
 **/
public class LoginAsapActivity extends AsapBaseActivity implements View.OnClickListener {


    @InjectView(R.id.appbar)
    AppBar appbar;
    @InjectView(R.id.ed_username)
    EditText edUsername;
    @InjectView(R.id.bt_send_code)
    Button btSendCode;
    @InjectView(R.id.ed_verify_code)
    EditText edVerifyCode;
    @InjectView(R.id.bt_login)
    Button btLogin;

    String mobile = "";
    String verifyCode = "";
    private boolean hasSendCode = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login_asap);
        ButterKnife.inject(this);

        setUpAppBar();


        btLogin.setOnClickListener(this);
        btSendCode.setOnClickListener(this);
    }

    private void setUpAppBar() {
        appbar.setLeftNavigation(0, v -> {
            //// TODO: 15/11/6
            finish();
        });
    }

    private boolean checkMobile() {

        mobile = edUsername.getText().toString().trim();

        if (TextUtils.isEmpty(mobile)) {
            edUsername.requestFocus();
            edUsername.setError(getString(R.string.username_error));
            return false;
        }
        return true;
    }

    private boolean checkVerifyCode() {
        verifyCode = edVerifyCode.getText().toString().trim();
        if (TextUtils.isEmpty(verifyCode)) {
            edVerifyCode.requestFocus();
            edVerifyCode.setError(getString(R.string.smscode_error));
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login:
                if (checkMobile() && checkVerifyCode()) {
                    login();
                }

                break;
            case R.id.bt_send_code:
                if (checkMobile()) {
                    btSendCode.setEnabled(false);
                    sendMesCode();
                    new Thread(new SmsThread()).start();
                }
                break;
        }
    }

    int second = 60;

    /**
     * 发送验证码的线程
     */
    private class SmsThread implements Runnable {
        @Override
        public void run() {
            while (second > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                second--;
                btSendCode.post(new Runnable() {
                    @Override
                    public void run() {
                        btSendCode.setText(String.valueOf(second).concat(getString(R.string.send_after)));
                        if (second == 0) {
                            second = 60;
                            btSendCode.setEnabled(true);
                            btSendCode.setText(R.string.resend_code);
                        }
                    }
                });
            }
        }
    }

    /**
     * 请求发送验证码
     */
    private void sendMesCode() {
        hasSendCode = true;
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        UserAuthService userService = creator.getService(UserAuthService.class);
        Observable.create((Subscriber<? super ResponseDataWrapper> subscriber) -> {
            ResponseDataWrapper response = userService.sendCode(mobile);
            subscriber.onNext(response);
            subscriber.onCompleted();
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(userResponseDataWrapper -> {
            if (userResponseDataWrapper.respcd.equals(ConstValue.RESPCD)) {
                Toaster.s(LoginAsapActivity.this, "发送成功");
            } else {
                Toaster.s(LoginAsapActivity.this, "发送失败");
            }
        }, throwable -> {
            Toaster.s(LoginAsapActivity.this, "未知错误");
            T.e(throwable.toString());
        });
    }

    private void login() {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        UserAuthService userService = creator.getService(UserAuthService.class);
        Observable.create((Subscriber<? super ResponseDataWrapper<User>> subscriber) -> {
            ResponseDataWrapper<User> response = userService.login(mobile, verifyCode);
            subscriber.onNext(response);
            subscriber.onCompleted();
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(userResponseDataWrapper -> {
            if (userResponseDataWrapper.respcd.equals(ConstValue.RESPCD)) {
                Toaster.s(LoginAsapActivity.this, "登陆成功");
                User.cacheUserId(userResponseDataWrapper.data.meruser);
                User.cacheUserToken(userResponseDataWrapper.data.token);
                User.cacheUserMobile(userResponseDataWrapper.data.mobile);
                MainActivity.REFRESH_ALL_FRAGMENT = 1;
                setResult(RESULT_OK);
                finish();
            } else {
                Toaster.s(LoginAsapActivity.this, "登陆失败");
            }
        }, throwable -> {
            Toaster.s(LoginAsapActivity.this, "未知错误");
            T.e(throwable.toString());
        });
    }

}
